<template>
    <div class="AItalk">
        <!-- <div class="chatMessage-area">
            
        </div> -->
        <!-- 后续聊天内容区域 -->
        <div class="chatContent_area" style="overflow: auto">
          <div 
            v-for="i in chat_message" 
            :key="i.id" 
            :class="{ 'style-robot': i.is_robot, 'style-user': !i.is_robot }"
            class="markdown-content">
            <!-- 修改文本渲染方式 -->
            <div v-html="marked(i.content, { breaks: true })"></div>
          </div>
        </div>
        <InputAear />
        
        
    </div>
</template>

<script setup lang="ts">
import {ref,onMounted, onUnmounted} from 'vue';
import {consult} from '../../tool/dk_require';
import { emitter } from '@/tool/emitters';
import type chatMessage from '../../tool/interface';
// import {chatAIserver} from '../../sever/chatAI/chatAI_server'
import InputAear from './InputArea.vue'

//引入唯一id生成工具
import {v4 as uuid} from 'uuid'
import { marked } from 'marked';
import axios from 'axios';
import {config} from '../../config';

let input_message = ref('');
let chat_message = ref<chatMessage[]>([])
let receivedBuffer = '';

let result = ref(''); //目标铐录内容
let real_result = ref('');  //铐录内容填充

let answer = ref(""); //后端返回的回答

//接收输入框输入文本内容
emitter.on('sen-content',async(value)=>{
  input_message.value = value as string;


  //接收用户输入内容
  chat_message.value.push({id:uuid(),is_robot:false,content: value as string})
  //将用户输入内容存入数据库

  console.log('【发送内容】',value)
  //请求回答
  let res = await getDSChat(value as string)
  console.log("【函数返回的数据】",res)

  

})

async function getDSChat(message:string){

    //新增回答
    chat_message.value.push({id:uuid(),is_robot:true,content: ""});

    await axios({
        method: 'post',
        url: config+'/api/getStreamChat', // 替换为实际API
        responseType: 'text',
        headers: {
            "Content-Type": "application/x-www-form-urlencoded" // 使用JSON格式
        },
        data: {
            message: message
        },
        onDownloadProgress: (progressEvent) => {
            // 获取新数据块
            const newText = progressEvent.event.currentTarget.responseText;
            
            // 计算新增内容
            const newContent = newText.substring(receivedBuffer.length);
            receivedBuffer = newText;
            
            // 处理新内容
            if (newContent) {
                // const messageElement = document.createElement('div');
                // messageElement.className = 'message';
                // messageElement.textContent = `数据块 ${++chunkCount}: ${newContent}`;
                // responseContent.appendChild(messageElement);
                // responseContent.scrollTop = responseContent.scrollHeight;
                // updateReceivedCount();

                // console.log("")
                // answer.value += newContent;
                chat_message.value[chat_message.value.length-1].content += newContent;
                console.log('收到数据块:', newContent);
                // return newContent;
            }
        }
    });

}


function copyPate() {
  console.log(result.value.length, chat_message.value[chat_message.value.length-1].content.length);
  if (chat_message.value[chat_message.value.length-1].content.length >= result.value.length) {

  // 退出递归
    return;
  } else {
  // stringA仍然比stringB短，进入下一次等待和递归
    setTimeout(()=>{
        //.charAt()用于获取字符串指定位置的字符
        chat_message.value[chat_message.value.length-1].content += result.value.charAt(chat_message.value[chat_message.value.length-1].content.length);
        copyPate();
    }, 50);
  }
}
// 添加窗口尺寸监听


const windowWidth = ref(window.innerWidth)

const handleResize = () => {
  windowWidth.value = window.innerWidth
}

// onMounted(async () => {
//   window.addEventListener('resize', handleResize)
//   let res = await chatAIserver.getRecReading();
//   let data = res.data
//   if(res.success){
//     console.log("【接收到的内容】",res.data)
//     console.log("【接收到的内容2】",data)
//     for(let i = 0;i < data.length;i++){
//       chat_message.value.push({id:data[i].id,is_robot:data[i].is_robot,content: data[i].message })
//     }
//   }
// })

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

</script>

<style scoped>
.AItalk {
  height: 100%;
  width: 100%;
  background-color: rgb(255, 255, 255);
  /* 新增flex布局 */
  display: flex;
  flex-direction: column;
  
}

.chatContent_area{
    
    width: 56%;
    position: relative;
    left: 49%;
    transform: translateX(-50%);
    min-width: 300px;
    z-index: 1000;
    margin-bottom: 260px;
    word-wrap: break-word; /* 超出宽度自动换行 */
    /* 同步响应式规则 */
    @media (max-width: 992px) {
        width: 72%;
    }
    @media (max-width: 768px) {
        width: 85%;
        min-width: unset;
    }
    @media (max-width: 480px) {
        width: 95%;
        
    }
}

.style-user {
    
    background-color: #a8edea;
    margin-left: 200px;
}

.style-robot {
  
  background-color: #ffffff;
  margin-left: 0px
}

</style>